
var pmx = require('pmx');
var pm2 = require('pm2');
var co  = require("co");
var os  = require("os");
var axon= require('axon');

var conf = pmx.initModule({
    // Options related to the display style on Keymetrics
    widget : {

        // Logo displayed
        logo : 'https://app.keymetrics.io/img/logo/keymetrics-300.png',

        // Module colors
        // 0 = main element
        // 1 = secondary
        // 2 = main border
        // 3 = secondary border
        theme            : ['#141A1F', '#222222', '#3ff', '#3ff'],

        // Section to show / hide
        el : {
            probes  : true,
            actions : true
        },

        // Main block to show / hide
        block : {
            actions : false,
            issues  : true,
            meta    : true,

            // Custom metrics to put in BIG
            main_probes : ['Logs Count', "logs_bytes"]
        }
    }
});

/**
 * Module specifics like connecting to a database and
 * displaying some metrics
 */

/**
 *                      Custom Metrics
 *
 * Let's expose some metrics that will be displayed into Keymetrics
 *   For more documentation about metrics: http://bit.ly/1PZrMFB
 */
var Probe = pmx.probe();



/**
 * .metric, .counter, .meter, .histogram are also available (cf doc)
 */
//发送日志总记录数
var logs_count = 0;
Probe.metric(
    {
        name: 'Logs Count',
        value: function() {
            return logs_count;
        }
    }
);

//发送日志总字节数
var logs_bytes = 0;
Probe.metric({
    name:   "Logs Bytes", 
    value:  function(){
        return logs_bytes;
    }
});


/**
 *                Simple Actions
 *
 *   Now let's expose some triggerable functions
 *  Once created you can trigger this from Keymetrics
 *
 */
pmx.action('env', function(reply) {
    return reply(process.env);
});

co(function*(){
    yield done => pm2.connect(done);

    console.log("connect to pm2");

    let std_maps = new Map();
    let apps = yield done => pm2.list(done);
    // apps.forEach(_ => {
    //     if (_.pm2_env.axm_options.isModule === true)
    //         return;
        
    //     let name = _.name;
    //     let out  = fs.createWriteStream(`./logs/${name}-out.log`, {flags: "a"});
    //     let err  = fs.createWriteStream(`./logs/${name}-err.log`, {flags: "a"});
    //     out.on("error", (e)=>{
    //         console.error(e.stack);
    //     });
    //     std_maps.set(name, {out, err});
    // });

    var sock = axon.socket('pub-emitter');
    var master_address = conf.master_address || "tcp://csh_omm:3000"
    sock.connect(master_address);

    let [sub, socket] = yield done => pm2.launchBus(done);
    sub.on("log:*", (type, packet)=>{
        ++logs_count;

        let data = packet.data;
        if (!data)
            return;

        logs_bytes += data.length;

        packet.host = os.hostname();
        sock.emit(`log:${type}`, packet);
    });

    while(true) yield done => setTimeout(done, 50, null);
}).catch(e=>{
    console.error(e.stack || e);
}).then(()=>{
    process.exit(1);
});
